package com.whty.cms.filewps.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


public class IpUtil {
    /**
     * @Author xiongxiaofei
     * @Date 2017/5/3
     * @Desc 获取本机IP
     */
    public static String getLocalIp() {
        String ipAddr = "127.0.0.1";
        try {
            List<String> ip4List = listLocalIp4();
            if (ip4List != null && ip4List.size() > 0) {
                ipAddr = ip4List.get(0);
            }
        } catch (Exception ex) {
        }
        return ipAddr;
    }

    /**
     * @author xiongxiaofei
     * @date 2017/3/3
     * @intro 获取本机所有IPv4的地址
     */
    public static List<String> listLocalIp4() {
        List<String> localIp4List = new ArrayList<>();
        Enumeration<NetworkInterface> networkInterfaceEnumeration;
        try {
            networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        } catch (Exception ex) {
            return localIp4List;
        }
        while (networkInterfaceEnumeration.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
            Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
            while (inetAddressEnumeration.hasMoreElements()) {
                InetAddress inetAddress = inetAddressEnumeration.nextElement();
                if (inetAddress instanceof Inet4Address) {
                    if (!"127.0.0.1".equals(inetAddress.getHostAddress())) {
                        localIp4List.add(inetAddress.getHostAddress());
                    }
                }
            }
        }
        return localIp4List;
    }

    /**
     * @author xiongxiaofei
     * @date 2017/3/3
     * @intro 获取本机MAC地址
     */
    public static String getLocalMac() {
        // 获取网卡，获取地址
        byte[] mac;
        try {
            mac = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
        } catch (Exception ex) {
            return null;
        }
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            //字节转换为整数
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                sb.append("0").append(str);
            } else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }


}
